use nacos_core::Result;
use nacos_cluster::manager::ClusterManager;
use nacos_cluster::node::ClusterNode;
use std::sync::Arc;
use tokio::time::{Duration, sleep};

#[tokio::main]
async fn main() -> Result<()> {
    println!("🎯 集群选举故障测试");
    println!("=".repeat(50));
    
    // 模拟集群节点
    let nodes = vec![
        ClusterNode::new("node1", "127.0.0.1:8848"),
        ClusterNode::new("node2", "127.0.0.1:8849"),
        ClusterNode::new("node3", "127.0.0.1:8850"),
    ];
    
    println!("📊 初始化集群节点:");
    for node in &nodes {
        println!("   🖥️  {}: {}", node.id, node.address);
    }
    
    // 创建集群管理器
    let cluster_manager = Arc::new(ClusterManager::new(
        nodes[0].clone(),
        nodes.clone(),
    ));
    
    // 启动集群
    println!("\n🚀 启动集群...");
    cluster_manager.start().await?;
    
    // 显示初始主节点
    let initial_leader = cluster_manager.get_current_leader().await;
    println!("👑 初始主节点: {}", initial_leader.map(|n| n.id).unwrap_or("无"));
    
    // 模拟节点状态检查
    println!("\n🔍 检查节点健康状态:");
    for node in &nodes {
        let is_healthy = cluster_manager.is_node_healthy(&node.id).await;
        println!("   {}: {}", node.id, 
            if is_healthy { "✅ 健康" } else { "❌ 故障" });
    }
    
    // 模拟主节点故障
    println!("\n⚡ 模拟主节点故障 (node1)...");
    cluster_manager.mark_node_failed("node1").await?;
    
    // 等待选举
    println!("⏳ 等待新主节点选举...");
    sleep(Duration::from_secs(3)).await;
    
    // 检查新主节点
    let new_leader = cluster_manager.get_current_leader().await;
    println!("👑 新主节点: {}", new_leader.map(|n| n.id).unwrap_or("无"));
    
    // 验证集群状态
    println!("\n📊 集群状态验证:");
    let cluster_status = cluster_manager.get_cluster_status().await?;
    println!("   总节点数: {}", cluster_status.total_nodes);
    println!("   健康节点数: {}", cluster_status.healthy_nodes);
    println!("   故障节点数: {}", cluster_status.failed_nodes);
    println!("   当前主节点: {}", cluster_status.current_leader);
    
    // 测试故障恢复
    println!("\n🔄 模拟故障节点恢复...");
    cluster_manager.mark_node_recovered("node1").await?;
    
    sleep(Duration::from_secs(2)).await;
    
    let recovered_status = cluster_manager.get_cluster_status().await?;
    println!("📈 恢复后状态:");
    println!("   健康节点数: {}", recovered_status.healthy_nodes);
    println!("   故障节点数: {}", recovered_status.failed_nodes);
    
    // 测试服务连续性
    println!("\n🧪 测试服务连续性:");
    let is_service_available = cluster_manager.is_service_available().await?;
    println!("   服务可用性: {}", 
        if is_service_available { "✅ 正常" } else { "❌ 中断" });
    
    // 清理
    cluster_manager.shutdown().await?;
    
    println!("\n🎯 集群选举故障测试完成！");
    
    Ok(())
}